<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\MoneyLog;
use app\common\model\OrderMore;
use app\common\model\Packages;
use app\common\model\UserPackagesConfig;
use fast\Random;
use think\db\Query;
use think\Validate;

/**
 * 创建订单
 */
class Order extends Api
{
    /**
     * Packages模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order();
    }

    protected $noNeedLogin = [
        'callback',
        'add',
        'orderSync',
        'callbackTwo',
        'cse',
        'callbackGth',
        'callbackKgj',
        'orderInfo',
        'orderInfo172',
        'ceshi'
    ];
    protected $noNeedRight = ['*'];

    //订单列表
    public function index()
    {
        $status           = input('status', '');
        $where['user_id'] = $this->auth->id;
        if ($status >= 0) {
            $where['order_status'] = $status;
        }

        $query        = $this->model->where($where);
        $package_name = input('package_name');
        if ($package_name) {
            $query = $query->where(['package_name' => ['like', '%'.$package_name.'%']]);
        }
        $shipping_phone = input('shipping_phone');
        if ($shipping_phone) {
            $query = $query->where(['shipping_phone' => $shipping_phone]);
        }
        $phone = input('phone');
        if ($phone) {
            $query = $query->where(['phone' => $phone]);
        }
        $shipping_contact = input('shipping_contact');
        if ($shipping_contact) {
            $query = $query->where(['shipping_contact' => $shipping_contact]);
        }
        $sta_time = input('sta_time');
        $end_time = input('end_time');

        if ($sta_time && $end_time) {
            $sta_time = strtotime($sta_time.' 00:00:01');
            $end_time = strtotime($end_time.' 23:59:59');
            $query    = $query->where('createtime', 'between time', [$sta_time, $end_time]);
        }
        $data = $query->with(['packages'])->order('id desc')->paginate(100)->each(function ($query){
            $goodsModel = new \app\admin\model\Packages();
            if($query->order_status == 5){
                $query->user_rebate = MoneyLog::where([
                    'user_id'  => $this->auth->id,
                    'order_id' => $query->id
                ])->value('money');
            }
            if($query->order_status == 4){
                $query->jiesuan_time_text = '上传截图后的'.$goodsModel->getDayList()[$query->packages->day];
            }
        });
        $this->success('ok', $data);
    }

    public function findSubordinatesWithLevel($userId, $level = 0, $user_name = '')
    {
        $subordinates = array ();

        if ($level == 0) {
            $where['id'] = $userId;
        } else {
            $where['parent_id'] = $userId;
        }
        if ($user_name) {
            $where['username'] = ['like', '%'.$user_name.'%'];
        }
        $results = db('user')->where($where)->field('id,parent_id,username')->select();
        foreach ($results as $result) {
            $result['level'] = $level; // 将层级信息添加到结果中
            $subordinates[]  = $result;
            $subordinates    = array_merge($subordinates,
                $this->findSubordinatesWithLevel($result['id'], $level + 1, $user_name));
        }

        return $subordinates;
    }

    //订单列表
    public function dailiindex()
    {
        $status = input('status', '');
//        $ids    = input('ids','');
//        $where['user_id|parent_id'] = $ids;

        $user_name = input('user_name');
        $ids       = input('ids', '');
        if (!$ids) {
            $this->error('缺少参数');
        }
//        if($user_name){
//            $level = 1;
//        }else{
//            $level = 0;
//        }
        $subordinates = $this->findSubordinatesWithLevel($ids);
        $string       = '';
        $result       = [];
        foreach ($subordinates as $k => $v) {
            $string                       .= ','.$v['id'];
            $result[$v['id']]['username'] = $v['username'];
            $result[$v['id']]['level']    = $v['level'];
        }
        $query = $this->model->whereIn('user_id', trim($string, ','));
        if ($status >= 0) {
            $query = $query->where(['order_status' => $status]);
        }
        $package_name = input('package_name');
        if ($package_name) {
            $query = $query->where(['package_name' => ['like', '%'.$package_name.'%']]);
        }
        $shipping_phone = input('shipping_phone');
        if ($shipping_phone) {
            $query = $query->where(['shipping_phone' => $shipping_phone]);
        }
        $phone = input('phone');
        if ($phone) {
            $query = $query->where(['phone' => $phone]);
        }
        $shipping_contact = input('shipping_contact');
        if ($shipping_contact) {
            $query = $query->where(['shipping_contact' => $shipping_contact]);
        }
        $sta_time = input('sta_time');
        $end_time = input('end_time');

        if ($sta_time && $end_time) {
            $sta_time = strtotime($sta_time.' 00:00:01');
            $end_time = strtotime($end_time.' 23:59:59');
            $query    = $query->where('createtime', 'between time', [$sta_time, $end_time]);
        }
        $data = $query->with(['packages'])->order('id desc')->paginate(15);
        if ($data) {
            $data = $data->toArray();
            foreach ($data['data'] as $kk => &$vv) {
                $vv['username'] = $result[$vv['user_id']]['username'];
                $vv['level']    = $result[$vv['user_id']]['level'];
                if ($vv['order_status'] == 5) {
                    $vv['user_rebate'] = MoneyLog::where(['user_id' => $ids, 'order_id' => $vv['id']])->value('money');
                }
            }

        }
        $this->success('ok', $data);
    }

    //办理套餐
    public function add()
    {
        $params   = $this->request->post();
        $validate = [
            ['id', 'require', '请传递套餐ID'],
            ['shipping_contact', 'require', '请填写办卡人姓名'],
            ['agid', 'require', '缺少参数'],
            ['shipping_phone', 'require|regex:/^1\d{10}$/', '请输入把卡人手机号|办卡人手机号格式不对'],
            //            ['shipping_idcard', 'require|regex:/^\d{17}[0-9xX]$/', '请输入办理人身份证|身份证号格式错误'],
            ['shipping_province', 'require', '请选择收货人省份'],
            ['shipping_city', 'require', '请选择收货人城市'],
            ['shipping_area', 'require', '请选择收货人地区'],
            ['shipping_address', 'require', '请输入收货人详情地址']
        ];
        $result   = $this->validate($params, $validate);
        if ($result !== true) {
            $this->error($result);
        }
        $packagesInfo = Packages::where(['id' => $params['id']])->find();
        $UserInfo     = \app\common\model\User::where(['id' => $params['agid']])->find();
        if (!$UserInfo) {
            $this->error('代理不存在');
        }
        if (!$packagesInfo) {
            $this->error('产品不存在');
        }
        if ($packagesInfo['platform_type'] == 8) {
            $this->addorderlianyun($packagesInfo, $params, $UserInfo);
        } else {
            if ($packagesInfo['platform_type'] == 4) {
                $this->addorder172($packagesInfo, $params, $UserInfo);
            } else {
                if ($packagesInfo['status'] != 1) {
                    $this->error('产品已下架');
                }

                $params['id']      = $packagesInfo['packages_id'];
                $data['appid']     = config('site.ooen_appid');
                $data['timestamp'] = time();
                $data['nonce_str'] = Random::alnum(32);
                $data              = array_merge($data, $params);
                $string            = ascll($data);
                $stringSignTemp    = $string.'&appsecret='.config('site.open_appsecret');;
                $data['sign'] = mb_strtoupper(md5($stringSignTemp));
                $url          = "http://agent.haoka.bx10086.cn/v1/haoka_api/packageOrder";//办理套餐
                $res          = httpPost($url, $data);
                $arr          = json_decode($res, true);
                if (!empty($arr['errcode'])) {
                    $this->error($arr['errmsg']);
                }
                if ($arr['errcode'] == 0) {
                    $user_rebate = UserPackagesConfig::where([
                        'user_id'     => $params['agid'],
                        'packages_id' => $packagesInfo['id']
                    ])->value('money');
                    if (!$user_rebate) {
                        if ($UserInfo['parent_id'] == 0) {
                            $user_rebate = $packagesInfo['rebate'];
                        } else {
                            $user_rebate = 0;
                        }
                    }
                    $params['user_id']      = $UserInfo['id'];
                    $params['goods_id']     = $packagesInfo['id'];
                    $params['order_id']     = $arr['order_id'];
                    $params['package_name'] = $packagesInfo['name'];
                    $params['parent_id']    = $UserInfo['parent_id'];
                    $params['user_rebate']  = $user_rebate;
                    unset($params['id'], $params['agid']);
                    $r = $this->model->create($params);

                    $order_id              = $r->id;
                    $inser_two['order_id'] = $order_id;
                    //顶级代理
                    $config                = new UserPackagesConfig();
                    $inser_two['goods_id'] = $packagesInfo['id'];
                    if (!$UserInfo['parent_id']) {
                        $money = $config->where('user_id', $UserInfo['id'])->where(['packages_id' => $packagesInfo['id']])->sum('money');
                        if (!$money) {
                            $money = $packagesInfo['rebate'];
                        }
                        $inser_two['user_id'] = $UserInfo['id'];
                        $inser_two['money']   = $money;
                        $inser_two['level']   = 10;//顶级代理自购
                        OrderMore::create($inser_two);
                    } else {
                        $packages_where['packages_id'] = $packagesInfo['id'];
                        if($UserInfo['three_id']){
                            $zhi_money = $config->where('user_id', $UserInfo['three_id'])->where($packages_where)->value('money');
                            if(!$zhi_money){
                                $zhi_money = $packagesInfo['rebate'];
                            }
                            $ding_money      = $config->where('user_id', $UserInfo['two_id'])->where($packages_where)->value('money');
                            if($ding_money){
                                //上三层
                                $inser_two['user_id'] = $UserInfo['three_id'];
                                $inser_two['money']   = $ding_money;
                                $inser_two['level']   = 9;
                                OrderMore::create($inser_two);
                            }else{
                                $ding_money = 0;
                            }

                            //二层
                            $two_money   = $config->where('user_id', $UserInfo['parent_id'])->where($packages_where)->value('money');
                            if($two_money){
                                $inser_two['user_id'] = $UserInfo['two_id'];
                                $inser_two['money']   = $two_money;
                                $inser_two['level']   = 8;
                                OrderMore::create($inser_two);
                            }else{
                                $two_money = 0;
                            }

                            //一层
                            $parent_money                  = $config->where('user_id', $UserInfo['id'])->where($packages_where)->value('money');
                            if($parent_money){
                                $inser_two['user_id']          = $UserInfo['parent_id'];
                                $inser_two['money']            = $parent_money;
                                $inser_two['level']   = 7;//直推
                                OrderMore::create($inser_two);
                            }else{
                                $parent_money = 0;
                            }
                            //自购
                            $inser_two['user_id']  = $UserInfo['id'];
                            $inser_two['money']    = $zhi_money - ($parent_money + $two_money + $ding_money);
                            $inser_two['level']    = 6;
                            OrderMore::create($inser_two);

                        }elseif ($UserInfo['two_id']){
                            //顶级佣金
                            $zhi_money = $config->where('user_id', $UserInfo['two_id'])->where($packages_where)->value('money');
                            if(!$zhi_money){
                                $zhi_money = $packagesInfo['rebate'];
                            }
                            //上二层
                            $two_money   = $config->where('user_id', $UserInfo['parent_id'])->where($packages_where)->value('money');
                            if($two_money){
                                $inser_two['user_id'] = $UserInfo['two_id'];
                                $inser_two['money']   = $two_money;
                                $inser_two['level']   = 8;
                                OrderMore::create($inser_two);
                            }else{
                                $two_money = 0;
                            }

                            //一层
                            $parent_money                  = $config->where('user_id', $UserInfo['id'])->where($packages_where)->value('money');
                            if($parent_money){
                                $inser_two['user_id']          = $UserInfo['parent_id'];
                                $inser_two['money']            = $parent_money;
                                $inser_two['level']   = 7;//直推
                                OrderMore::create($inser_two);
                            }else{
                                $parent_money = 0;
                            }
                            //自购
                            $inser_two['user_id']  = $UserInfo['id'];
                            $inser_two['money']    = $zhi_money -  (bcadd($parent_money, $two_money));
                            $inser_two['level']    = 6;
                            OrderMore::create($inser_two);
                        }else{
                            //顶级
                            $parent_money   = $config->where('user_id', $UserInfo['parent_id'])->where($packages_where)->value('money');
                            if(!$parent_money){
                                $parent_money = $packagesInfo['rebate'];
                            }
                            $one_money                     = $config->where('user_id', $UserInfo['id'])->where($packages_where)->value('money')??0;
                            if($one_money){
                                $inser_two['user_id']      = $UserInfo['parent_id'];
                                $inser_two['money']        = $one_money;
                                $inser_two['level']        = 7;//直推
                                OrderMore::create($inser_two);
                            }
                            //自购
                            $inser_two['level']        = 6;//自购
                            $inser_two['user_id']      = $UserInfo['id'];
                            $inser_two['money']        = $parent_money - $one_money;
                            OrderMore::create($inser_two);
                        }
                    }
                }
            }
        }
        $this->success('申领成功');
    }


    public function orderSync()
    {
        $params   = $this->request->post();
        $validate = [
            ['cardType', 'require', '请传递套餐ID'],
            ['provinceName', 'require', '请填写办卡人姓名'],
            ['provinceName', 'require', '缺少参数'],
            ['cityName', 'require', '缺少参数'],
            //            ['number', 'require', '缺少参数'],
            ['agid', 'require', '缺少参数'],
            ['certName', 'require', '缺少参数'],
            ['certNo', 'require', '缺少参数'],
            ['postProvinceName', 'require', '缺少参数'],
            ['postCityName', 'require', '缺少参数'],
            ['postDistrictName', 'require', '缺少参数'],
            ['postAddr', 'require', '缺少参数'],
            ['contactNum', 'require', '缺少参数']
        ];
        $result   = $this->validate($params, $validate);
        if ($result !== true) {
            $this->error($result);
        }
        $info = Packages::where(['id' => $params['cardType'], 'status' => 1])->find();
        if (!$info) {
            $this->error('产品不存在或已下架');
        }
        $UserInfo = \app\common\model\User::where(['id' => $params['agid']])->find();
        if (!$UserInfo) {
            $this->error('代理不存在');
        }

        if (empty($params['number'])) {
            $params['number'] = '';
        }

        if ($info['platform_type'] == 2) {
            $params['partnerId'] = config('site.hao2_partnerId');
            $secret              = config('site.hao2_secret');
            $url                 = config('site.hao2_url').'/orderSync';
        } elseif ($info['platform_type'] == 3) {
            $params['partnerId'] = config('site.hao3_partnerId');
            $secret              = config('site.hao3_secret');
            $url                 = config('site.site.hao3_url')."/orderSync";
        } elseif ($info['platform_type'] == 4) {
            $this->addorder172($info, $params, $UserInfo);
        } elseif ($info['platform_type'] == 6) {
            $this->kgjcreateOrder($info, $params, $UserInfo);
        } elseif ($info['platform_type'] == 7) {
            $this->self_help($info, $params, $UserInfo);
        }
        $params['postProvinceName'] = str_replace('省', '', $params['postProvinceName']);
        $params['provinceName']     = str_replace('省', '', $params['provinceName']);

        if ($params['cityName'] == "市辖区" || $params['cityName'] == "县") {
            $params['postCityName']     = $params['provinceName'];
            $params['cityName']         = $params['provinceName'];
            $params['postProvinceName'] = str_replace('市', '', $params['provinceName']);
        }
        if ($info['id'] == 343 || $info['id'] == 345) {
            $params['provinceName'] = "海南"; //省
            $params['cityName']     = "三亚市";//市
        }
        if ($info['id'] == 165) {
            $params['provinceName'] = "浙江"; //省
            $params['cityName']     = "宁波市";//市
//            $params['postDistrictName'] = '';
        }
        if ($info['id'] == 371) {
            $params['provinceName'] = "湖南"; //省
            $params['cityName']     = "长沙市";//市
//            $params['postDistrictName'] = '';
        }
        if ($info['id'] == 440 || $info['id'] == 441) {
            $params['provinceName'] = "广东"; //省
            $params['cityName']     = "广州市";//市
//            $params['postDistrictName'] = '';
        }
        if ($info['province_name']) {
            $params['provinceName'] = $info['province_name'];
        }
        if ($info['city_name']) {
            $params['cityName'] = $info['city_name'];//市
        }
        $params['cardType'] = (int)$info['packages_id'];
        ksort($params);//升序排序
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $k.$v;
        }
        $str            = $secret.$str.$secret;  //abc123cardType4cityName郑州市pageNo1partnerId1proniceName河南searchValue4150222abc123
        $sign           = strtoupper(md5($str)); //93932E8BD15A2EBE6D0C4F3890B97D90
        $params['sign'] = $sign;
        if ($this->auth->id == 203) {
//            dump($params);exit();
            $res['data']['orderId'] = time();
        }else{
            $res = json_decode(httpPost($url, $params), true);
        }
//        dump($params);exit();
        if (!empty($res['data']['orderId'])) {
            $this->model->orderCreateAdd($params, $UserInfo, $info, $res['data']['orderId']);
            $this->success('下单成功');
        }
        $this->error($res['info']);
    }


    //172下单
    public function addorder172($goods, $params, $UserInfo)
    {
        $url                 = config('site.url_172');
        $key                 = config('site.key_172');
        $user_id             = config('site.zhanghao_172');
        $data['user_id']     = $user_id;
        $data['Timestamp']   = time();
        $data['Name']        = $params['certName'];        //姓名
        $data['Phone']       = $params['contactNum'];      //办卡人手机号
        $data['IDCard']      = $params['certNo'];          //身份证号
        $data['Province']    = $params['provinceName'];    //省
        $data['City']        = $params['postCityName'];    //市
        $data['Area']        = $params['postDistrictName'];//区县
        $data['Address']     = $params['postAddr'];        //详细地址
        $data['ProductID']   = $goods['packages_id'];
        $data['DownOrderID'] = 'z'.$this->auth->id.time();
        $data['ThirdPhone']  = '';
        $string              = ascll172($data);
        $data['user_sign']   = strtolower(md5($string.$key));
        if ($UserInfo['id'] == 203) {
            $arr['message'] = time();
            $arr['code']    = 0;
        } else {
            $url = $url.'/api/order/ApiToOrder';
            $res = httpPost($url, $data);
            $arr = json_decode($res, true);
        }
//        $arr = cache('pt172');
        if (!empty($arr['message']) && $arr['code'] == 0) {
//            $params['down_order_id'] = $data['DownOrderID'];
//            $params['user_id']       = $UserInfo['id'];
//            $params['goods_id']      = $goods['id'];
//            $params['order_id']      = $arr['message'];
//            $params['package_name']  = $goods['name'];
//            $params['parent_id']     = $UserInfo['parent_id'];
//            $params['user_rebate']   = 10;
//            $params['platform_type'] = $goods['platform_type'];
//            unset($params['id'],$params['agid']);

            $this->model->orderCreateAdd($params, $UserInfo, $goods, $arr['message']);
//            $this->model->create($params);
            $this->success('申领成功');
        } else {
            $this->error('开卡失败：'.$arr['message']);
        }
    }

    /**
     * @menu 联运下单
     * @Author:男人的坏
     * @Date:2024-05-14 15:18
     */
    public function addorderlianyun($packagesInfo, $params, $UserInfo)
    {

        $url                        = config('site.yunlian_url')."/webman/api/package/channel/order_create";
        $data['channel_uuid']       = config('site.yunlian_zh');
        $data['key']                = config('site.yunlian_key');
        $data['timestamp']          = time();
        $data['sign']               = md5($data['channel_uuid'].$data['key'].$data['timestamp']);
        $data['payType']            = 0;
        $data['platform']           = 0;
        $data['id']                 = $packagesInfo['packages_id'];
        $data['certName']           = $params['shipping_contact'];        //姓名
        $data['receiveName']        = $params['shipping_contact'];        //姓名
        $data['receiveMobile']      = $params['shipping_phone'];          //办卡人手机号
        $data['certNo']             = $params['shipping_idcard'];         //身份证
        $data['receiveRegionCodes'] = [
            (int)$params['province_code'],
            (int)$params['city_code'],
            (int)$params['area_code']
        ];
        $data['receiveRegionNames'] = [
            $params['shipping_province'],
            $params['shipping_city'],
            $params['shipping_area']
        ];
        $data['receiveAddress'] = $params['shipping_address'];
        $res = postJson($url, $data);
        if (isset($res['code']) && $res['code'] == 1) {
            $params['order_id']     = $res['data'];
            $params['user_id']      = $UserInfo['id'];
            $params['goods_id']     = $packagesInfo['id'];
            $params['order_id']     = $res['data']['sn'];
            $params['package_name'] = $packagesInfo['name'];
            $params['parent_id']    = $UserInfo['parent_id'];
            unset($params['id'], $params['agid'],$params['province_code'],$params['area_code'],$params['city_code']);
            $params['platform_type'] = 8;
            $this->model->orderAddtwo($params,$packagesInfo, $UserInfo);
            $this->success('申领成功');
        } else {
            $this->error('开卡失败：'.$res['msg']);
        }
    }

    public function orderInfo()
    {
        $params            = input('post.');
        $data['appid']     = config('site.ooen_appid');
        $data['timestamp'] = time();
        $data['nonce_str'] = Random::alnum(32);
        $data              = array_merge($data, $params);
        $string            = ascll($data);
        $stringSignTemp    = $string.'&appsecret='.config('site.open_appsecret');;
        $data['sign'] = mb_strtoupper(md5($stringSignTemp));
        $url          = "http://agent.haoka.bx10086.cn/v1/haoka_api/orders";//办理套餐
        $res          = httpPost($url, $data);
        $rows         = json_decode($res, true);
//        dump($rows);exit();

//        $rows = $rows['rows'][0];
//        if(strpos($rows['remark'],'激活') !== false || strpos($rows['remark'],'首充') !== false || strpos($rows['remark'],'充值') !== false){
////            $up['order_status'] = 5;
////            $up['jiesuan_time'] = time();
//            $v = db('order')->where(['order_id'=>$rows['order_id']])->find();
//            if($v['user_rebate'] > 0){
//                $this->digui($v['user_id'], $v['user_rebate'],$v['goods_id'],$v['id']);
//            }else{
//                $this->diguitwo($v['user_id'],$v['goods_id'],$v['id']);
//            }
//        }else{
//            echo "33";
//        }
//
//        exit();
        $this->success('ok', $rows);
    }


    public function orderInfo172()
    {
        $url                 = config('site.url_172');
        $key                 = config('site.key_172');
        $user_id             = config('site.zhanghao_172');
        $data['user_id']     = $user_id;
        $data['Timestamp']   = time();
        $data['DownOrderID'] = 'mlkj2401171553326570';
        $string              = ascll172($data);
        $data['user_sign']   = strtolower(md5($string.$key));
        $url                 = $url.'/api/order/GetOrderInfo';
        $res                 = httpPost($url, $data);
        $arr                 = json_decode($res, true);
        if (!empty($arr['data']['orderNo'])) {
            $orderInfo = $this->model->with(['packages'])->where(['order_id' => $arr['data']['orderNo']])->find();
            if ($orderInfo) {
                //待处理、已提运营商～待处理
                //
                //已发货、已完成～待收货
                //
                //已撤单、审核不通过、已取消、无法结算～失败（要调取显示原因）
                //
                //已结算～已核销
                if ($arr['data']['remark']) {
                    $orderInfo->remark = $arr['data']['remark'];
                }
                if ($arr['data']['orderStatus'] == "审核不通过" || $arr['data']['orderStatus'] == "已撤单" || $arr['data']['orderStatus'] == "已取消" || $arr['data']['orderStatus'] == "无法结算") {
                    $orderInfo->order_status = 0;
                } elseif ($arr['data']['orderStatus'] == '已发货' || $arr['data']['orderStatus'] == '已完成') {
                    $orderInfo->order_status = 2;
                } elseif ($arr['data']['orderStatus'] == '待处理' || $arr['data']['orderStatus'] == '已提运营商') {
                    $orderInfo->order_status = 3;
                } elseif ($arr['data']['orderStatus'] == '已结算') {
                    if ($orderInfo['packages']['hexiao_day'] && $orderInfo['audit_upload_time']) {
                        $kai_time = $orderInfo['audit_upload_time'] + 86400 * $orderInfo['packages']['hexiao_day'];
                        if (time() > strtotime(date("Y-m-d", $kai_time))) {
                            $orderInfo->is_hexiao = 3;
                        } else {
                            $orderInfo->is_hexiao = 2;
                        }
                    }
                }
                if ($arr['data']['expressName']) {
                    $orderInfo->shipping_company_name = $arr['data']['expressName'];
                }
                if ($arr['data']['expressCode']) {
                    $orderInfo->shipping_no = $arr['data']['expressName'];
                }
                if ($arr['data']['thirdPhone']) {
                    $orderInfo->phone = $arr['data']['thirdPhone'];
                }
                $orderInfo->order_info_json = json_encode($arr['data'], true);
                $orderInfo->save();
            }
        }
    }

    public function diguitwo($user_id, $goods_id, $order_id)
    {
        $userModel    = new \app\common\model\User();
        $PackagesInfo = Packages::where(['id' => $goods_id])->find();
        if ($PackagesInfo) {
            $userInfo = $userModel->where(['id' => $user_id])->find();
            if ($userInfo['parent_id'] > 0) {
                return $this->diguitwo($userInfo['parent_id'], $goods_id, $order_id);
            }
            $userModel->money($PackagesInfo['rebate'], $user_id, '日结订单结算佣金');
        }
    }

    public function digui($user_id, $money, $goods_id, $order_id, $key = 0)
    {
        $userModel    = new \app\common\model\User();
        $config       = new UserPackagesConfig();
        $PackagesInfo = Packages::where(['id' => $goods_id])->find();
        if ($PackagesInfo) {
            if ($money > 0) {
                $userInfo = $userModel->where(['id' => $user_id])->find();
                $userModel->money($money, $user_id, '日结订单结算佣金');
                $key += 1;
                if ($userInfo['parent_id'] > 0) {
                    $configInfo = $config->where([
                        'user_id'     => $userInfo['parent_id'],
                        'packages_id' => $PackagesInfo['id']
                    ])->find();
                    if ($configInfo) {
                        $money = $configInfo['money'] - $money;
                    }
                    return $this->digui($userInfo['parent_id'], $money, $goods_id, $order_id, $key);
                }
            }
        }
    }


    public function callback()
    {
        cache('callback', $_POST);
        if (!empty($_POST['order_id'])) {
            $order = db('order')->where(['order_id' => $_POST['order_id']])->find();
            if ($order) {
                $rows               = $_POST;
                $up['order_status'] = $rows['order_status'];
                if (strpos($rows['remark'], '已激活') !== false) {
                    $up['order_status'] = 1;
                }
                if (strpos($rows['remark'], '待归档') !== false) {
                    $up['order_status'] = 1;
                }
                if (strpos($rows['remark'], '充值') !== false) {
                    $up['order_status'] = 4;
                    $up['jiesuan_time'] = time();
                }
                $up['order_info_json']   = json_encode($_POST, true);
                $up['order_status_text'] = $rows['order_status_text'];
                $up['rebate']            = $rows['rebate'];
                $up['channel']           = $rows['channel'];
                $up['remark']            = $rows['remark'];
                $up['package_name']      = $rows['package_name'];
                if (!empty($rows['shipping_no'])) {
                    $up['shipping_no'] = $rows['shipping_no'];
                }
                if (!empty($rows['shipping_company_name'])) {
                    $up['shipping_company_name'] = $rows['shipping_company_name'];
                }
                $up['is_recharged'] = $rows['is_recharged'];
                db('order')->where(['id' => $order['id']])->update($up);
            }
        }
    }

    public function callbackTwo()
    {
        cache('callbackTwo', file_get_contents('php://input'));
        $data = file_get_contents('php://input');
        $this->cse($data);
    }

    public function callbackGth()
    {
        cache('callbackGth', file_get_contents('php://input'));
//        $data = file_get_contents('php://input');
        echo "SUCCESS";
    }

    public function callbackKgj()
    {
        cache('callbackKgj', file_get_contents('php://input'));
//        $data = file_get_contents('php://input');
//        dump( json_decode(cache('callbackKgj'),true));exit();
        echo "SUCCESS";
    }

    public function cse($data)
    {
        $data = json_decode($data, true);
        if ($data) {
            $orderInfo = \app\common\model\Order::where(['order_id' => $data['orderId']])->find();
            if ($orderInfo) {
                if ($orderInfo['order_status'] == 0 || $orderInfo['order_status'] == 5) {
//                        echo "订单已更新";
                    $orderInfo->order_info_json = json_encode($data, true);
                    $orderInfo->save();
                    return;
                }
                if (!empty($orderInfo['packages'])) {
                    if ($orderInfo['packages']['platform_type'] == 2) {
                        $secret = config('site.hao2_secret');
                    } else {
                        $secret = "lQiUQJsnOqIaBqoU";
                    }
                }
                $send_sign = $data['sign'];

                unset($data['sign']);

                ksort($data);//字典排序,升序排列
                $str = '';
                foreach ($data as $k => $vv) {
                    $str .= $k.$vv;
                }
                $sign = strtoupper(md5($secret.$str.$secret));//签名
//                if ($sign == $send_sign) {
                    if (isset($data['state'])) {
                        if ($data['state'] == 0) {
                            $orderInfo->order_status = 3;
                        } else {
                            if ($data['state'] == 11) {
                                $orderInfo->order_status = 2;
                            } else {
                                if ($data['state'] == 1 || $data['state'] == 10) {
                                    $orderInfo->order_status = 1;
                                } else {
                                    if ($data['state'] == 6) {
                                        $packagesModel           = new \app\admin\model\Packages();
                                        $packageInfo             = $packagesModel->where(['id' => $orderInfo['goods_id']])->find();
                                        $orderInfo->order_status = 5;
                                        if ($orderInfo->is_agency == 1) {
                                            $orderInfo->settlement_time = time();
                                            $orderInfo->is_hexiao       = 2;
                                            orderfencheng($orderInfo->id, $orderInfo->goods_id);
                                        } else {
                                            $userModel = new \app\common\model\User();
                                            if ($orderInfo->audit_status != 2) {
                                                $orderInfo->order_status             = 4;
                                                $orderInfo->is_tripartite_settlement = 1;
                                            } else {
                                                $orderInfo->settlement_time = time();
                                                $orderInfo->is_hexiao       = 2;
                                                if ($orderInfo->is_more == 2) {
                                                    $orderInfo->two_js_time = settlement_time($orderInfo->settlement_time);
                                                    $huafei                 = $packageInfo['bxhf_text'];
                                                    $orderInfo->is_hexiao   = 5;
                                                    $orderInfo->more_num    = 1;
                                                    if ($packageInfo['day'] != 6) {
                                                        $orderInfo->hexiao_next_time = 7 * 86400 + time();
                                                    } else {
                                                        $orderInfo->hexiao_next_time = $orderInfo->two_js_time;
                                                    }
                                                } else {
                                                    $huafei = bcadd($packageInfo['ciyue_set_meal'],
                                                        $packageInfo['bxhf_text']);
                                                }
                                                if ($huafei) {
                                                    $userModel::money($huafei, $orderInfo->user_id, '话费报销',
                                                        $orderInfo->id,
                                                        $packageInfo['id']);
                                                    $orderInfo->baoxiao_time   = time();
                                                    $orderInfo->baoxiao_status = 2;
                                                }
                                                $v                     = $orderInfo;
                                                $userInfo              = $userModel->where(['id' => $v['user_id']])->find();
                                                $zigou_commission      = $packageInfo['one_commission'] ?? 0;
                                                $one_commission        = $packageInfo['junior_contribution'] ?? 0;
                                                $tjyj                  = $packageInfo['junior_contribution_tow'] ?? 0;
                                                $pplots_profit         = $packageInfo['pplots_profit'] ?? 0;
                                                $pplots_yunying_profit = $packageInfo['pplots_yunying_profit'] ?? 0;
                                                if ($packageInfo['duoci'] || $v->is_more == 2) {
                                                    jiangli($v, $packageInfo);
                                                    if ($v['parent_id']) {
                                                        jiangli($v, $packageInfo, 2);
                                                    }
                                                    if ($v['two_id']) {
                                                        jiangli($v, $packageInfo, 3);
                                                    }
                                                    //区县
                                                    if ($v['agency_area_id']) {
                                                        jiangli($v, $packageInfo, 4);
                                                    }
                                                    //小区
                                                    if ($v['plot_id']) {
                                                        jiangli($v, $packageInfo, 5);
                                                    }
                                                } else {
                                                    if ($userInfo) {
                                                        if ($zigou_commission) {
                                                            $userModel::money($zigou_commission, $v['user_id'],
                                                                '自购奖励', $v['id'], $packageInfo['id']);
                                                        }
                                                        if ($userInfo['parent_id'] && $one_commission) {
                                                            $userModel::money($one_commission, $userInfo['parent_id'],
                                                                '推荐有奖', $v['id'], $packageInfo['id']);
                                                        }
                                                        if ($userInfo['two_id'] && $tjyj) {
                                                            $userModel::money($tjyj, $userInfo['two_id'],
                                                                '推荐有奖', $v['id'], $packageInfo['id']);
                                                        }
                                                    }
                                                    if ($v['agency_area_id'] && $pplots_profit) {
                                                        $userModel::money($pplots_profit, $v['agency_area_id'],
                                                            '区县运营分润', $v['id'],
                                                            $packageInfo['id']);
                                                    }
                                                    if ($v['plot_id'] && $pplots_yunying_profit) {
                                                        $userModel::money($pplots_yunying_profit, $v['plot_id'],
                                                            '小区运营分润', $v['id'],
                                                            $packageInfo['id']);
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        if ($data['state'] == 4) {

                                            $orderInfo->order_status = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (isset($data['number'])) {
                        $orderInfo->phone = $data['number'];
                    }

                    if (isset($data['wlCompany'])) {
                        $orderInfo->shipping_company_name = $data['wlCompany'];
                    }
                    if (isset($data['wlOrderid'])) {
                        $orderInfo->shipping_no = $data['wlOrderid'];
                        if ($orderInfo->order_status == 1 || $orderInfo->order_status == 3) {
                            $orderInfo->order_status = 2;
                        }
                    }
                    if (isset($data['createtime'])) {
                        $orderInfo->callback_time = strtotime($data['createtime']);
                    }
                    if (isset($data['lgtsId'])) {
                        $orderInfo->lgtsId = $data['lgtsId'];
                    }
                    if (isset($data['info'])) {
                        $orderInfo->remark = $data['info'];
                    }
                    if (isset($data['actime'])) {
                        $orderInfo->actime = $data['actime'];
                    }

                    $orderInfo->order_info_json = json_encode($data, true);
                    $r                          = $orderInfo->save();
                    if ($r) {
                        echo "更新成功";
                    }
//                } else {
//                    echo "签名失败";
//                }
            }
        }
    }

    public function ceshi()
    {
//        $data = json_decode($data, true);
        $data['orderId'] = '1713408668';
        $data['state']   = 6;
        $data['sign']    = 1;
        if ($data) {
            $orderInfo = \app\common\model\Order::where(['order_id' => $data['orderId']])->find();
            if ($orderInfo) {
                if ($orderInfo['order_status'] == 0 || $orderInfo['order_status'] == 5) {
//                        echo "订单已更新";
                    $orderInfo->order_info_json = json_encode($data, true);
                    $orderInfo->save();
                    return;
                }
                if (!empty($orderInfo['packages'])) {
                    if ($orderInfo['packages']['platform_type'] == 2) {
                        $secret = config('site.hao2_secret');
                    } else {
                        $secret = "lQiUQJsnOqIaBqoU";
                    }
                }
                $send_sign = $data['sign'];

                unset($data['sign']);

                ksort($data);//字典排序,升序排列
                $str = '';
                foreach ($data as $k => $vv) {
                    $str .= $k.$vv;
                }
                $sign      = strtoupper(md5($secret.$str.$secret));//签名
                $send_sign = 1;
                $sign      = 1;
                if ($sign == $send_sign) {
                    if (isset($data['state'])) {
                        if ($data['state'] == 0) {
                            $orderInfo->order_status = 3;
                        } else {
                            if ($data['state'] == 11) {
                                $orderInfo->order_status = 2;
                            } else {
                                if ($data['state'] == 1 || $data['state'] == 10) {
                                    $orderInfo->order_status = 1;
                                } else {
                                    if ($data['state'] == 6) {
                                        $packagesModel           = new \app\admin\model\Packages();
                                        $packageInfo             = $packagesModel->where(['id' => $orderInfo['goods_id']])->find();
                                        $orderInfo->order_status = 5;
                                        if ($orderInfo->is_agency == 1) {
                                            $orderInfo->settlement_time = time();
                                            $orderInfo->is_hexiao       = 2;
                                            $userData                   = findAncestors($orderInfo['user_id']);
                                            if (!$userData) {
                                                //顶级代理下单
                                                dingji($orderInfo['user_id'], $orderInfo['id'], $orderInfo['goods_id'],
                                                    $packageInfo['rebate'], false, true);
                                            } else {
                                                array_unshift($userData, $orderInfo['user_id']);
                                                $money = moneydigui($orderInfo['user_id'], $orderInfo['goods_id']);
                                                if ($money) {
                                                    digui($orderInfo['user_id'], $money, $orderInfo['goods_id'],
                                                        $orderInfo['id'], 0, true);
                                                } else {
                                                    //顶级
                                                    dingji($userData[count($userData) - 1], $orderInfo['id'],
                                                        $orderInfo['goods_id'], $packageInfo['rebate'], false, true);
                                                }
                                            }
                                        } else {
                                            if ($orderInfo->is_verification == 0) {
                                                $orderInfo->is_hexiao = 2;
                                            } else {
                                                $orderInfo->is_hexiao = 5;
                                            }
                                            $userModel = new \app\common\model\User();
//                                            if($orderInfo->audit_status != 2){
//                                                $orderInfo->order_status             = 4;
//                                                $orderInfo->is_tripartite_settlement = 1;
//                                            }else{
                                            $orderInfo->settlement_time = time();

                                            if ($orderInfo->is_more == 2) {
                                                $orderInfo->two_js_time = settlement_time($orderInfo->settlement_time);
                                                $huafei                 = $packageInfo['bxhf_text'];
                                                $orderInfo->more_num    = 1;
                                                if ($packageInfo['day'] != 6) {
                                                    $orderInfo->hexiao_next_time = 7 * 86400 + time();
                                                } else {
                                                    $orderInfo->hexiao_next_time = $orderInfo->two_js_time;
                                                }
                                            } else {
                                                $huafei = bcadd($packageInfo['ciyue_set_meal'],
                                                    $packageInfo['bxhf_text']);
                                            }
                                            if ($huafei) {
                                                $userModel::money($huafei, $orderInfo->user_id, '话费报销', $orderInfo->id,
                                                    $packageInfo['id']);
                                                $orderInfo->baoxiao_time   = time();
                                                $orderInfo->baoxiao_status = 2;
                                            }
                                            $v = $orderInfo;
                                            jiangli($v, $packageInfo);
                                            if ($v['parent_id']) {
                                                jiangli($v, $packageInfo, 2);
                                            }
                                            if ($v['two_id']) {
                                                jiangli($v, $packageInfo, 3);
                                            }
                                            //区县
                                            if ($v['agency_area_id']) {
                                                jiangli($v, $packageInfo, 4);
                                            }
                                            //小区
                                            if ($v['plot_id']) {
                                                jiangli($v, $packageInfo, 5);
                                            }
//                                                $userInfo              = $userModel->where(['id' => $v['user_id']])->find();
//                                                $zigou_commission      = $packageInfo['one_commission'] ?? 0;
//                                                $one_commission        = $packageInfo['junior_contribution'] ?? 0;
//                                                $tjyj                  = $packageInfo['junior_contribution_tow'] ?? 0;
//                                                $pplots_profit         = $packageInfo['pplots_profit'] ?? 0;
//                                                $pplots_yunying_profit = $packageInfo['pplots_yunying_profit'] ?? 0;
//                                                if ($packageInfo['duoci'] || $v->is_more == 2) {
//                                                    jiangli($v, $packageInfo);
//                                                    if ($v['parent_id']) {
//                                                        jiangli($v, $packageInfo, 2);
//                                                    }
//                                                    if ($v['two_id']) {
//                                                        jiangli($v, $packageInfo, 3);
//                                                    }
//                                                    //区县
//                                                    if ($v['agency_area_id']) {
//                                                        jiangli($v, $packageInfo, 4);
//                                                    }
//                                                    //小区
//                                                    if ($v['plot_id']) {
//                                                        jiangli($v, $packageInfo, 5);
//                                                    }
//                                                }else{
//                                                    if ($userInfo) {
//                                                        if ($zigou_commission) {
//                                                            $userModel::money($zigou_commission, $v['user_id'],
//                                                                '自购奖励', $v['id'], $packageInfo['id']);
//                                                        }
//                                                        if ($userInfo['parent_id'] && $one_commission) {
//                                                            $userModel::money($one_commission, $userInfo['parent_id'],
//                                                                '推荐有奖', $v['id'], $packageInfo['id']);
//                                                        }
//                                                        if ($userInfo['two_id'] && $tjyj) {
//                                                            $userModel::money($tjyj, $userInfo['two_id'],
//                                                                '推荐有奖', $v['id'], $packageInfo['id']);
//                                                        }
//                                                    }
//                                                    if ($v['agency_area_id'] && $pplots_profit) {
//                                                        $agencyInfo = \app\admin\model\user\Agency::where(['user_id'=>$v['agency_area_id']])->find();
//                                                        if($agencyInfo['money'] > $pplots_profit){
//                                                            if($agencyInfo->money > $pplots_profit){
//                                                                $agencyInfo->money -= $pplots_profit;
//                                                                $agencyInfo->save();
//                                                                $pplots_profit = 0;
//                                                            }else{
//                                                                $pplots_profit = $pplots_profit - $agencyInfo->money;
//                                                                $agencyInfo->money = 0;
//                                                                $agencyInfo->save();
//                                                            }
//                                                        }
//                                                        if($pplots_profit){
//                                                            $userModel::money($pplots_profit, $v['agency_area_id'], '区县运营分润', $v['id'],
//                                                                $packageInfo['id']);
//                                                        }
//                                                    }
//                                                    if ($v['plot_id'] && $pplots_yunying_profit) {
//                                                        $agencyInfo = \app\admin\model\user\Agency::where(['user_id'=>$v['plot_id']])->find();
//                                                        if($agencyInfo['money'] > $pplots_yunying_profit){
//                                                            if($agencyInfo->money > $pplots_yunying_profit){
//                                                                $agencyInfo->money -= $pplots_yunying_profit;
//                                                                $agencyInfo->save();
//                                                                $pplots_yunying_profit = 0;
//                                                            }else{
//                                                                $pplots_yunying_profit = $pplots_yunying_profit - $agencyInfo->money;
//                                                                $agencyInfo->money = 0;
//                                                                $agencyInfo->save();
//                                                            }
//                                                        }
//                                                        if($pplots_yunying_profit){
//                                                            $userModel::money($pplots_yunying_profit, $v['plot_id'], '小区运营分润', $v['id'],
//                                                                $packageInfo['id']);
//                                                        }
//                                                    }
//                                                }
//                                            }
                                        }
                                    } else {
                                        if ($data['state'] == 4) {

                                            $orderInfo->order_status = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (isset($data['number'])) {
                        $orderInfo->phone = $data['number'];
                    }

                    if (isset($data['wlCompany'])) {
                        $orderInfo->shipping_company_name = $data['wlCompany'];
                    }
                    if (isset($data['wlOrderid'])) {
                        $orderInfo->shipping_no = $data['wlOrderid'];
                        if ($orderInfo->order_status == 1 || $orderInfo->order_status == 3) {
                            $orderInfo->order_status = 2;
                        }
                    }
                    if (isset($data['createtime'])) {
                        $orderInfo->callback_time = strtotime($data['createtime']);
                    }
                    if (isset($data['lgtsId'])) {
                        $orderInfo->lgtsId = $data['lgtsId'];
                    }
                    if (isset($data['info'])) {
                        $orderInfo->remark = $data['info'];
                    }
                    if (isset($data['actime'])) {
                        $orderInfo->actime = $data['actime'];
                    }

                    $orderInfo->order_info_json = json_encode($data, true);
                    $r                          = $orderInfo->save();
                    if ($r) {
                        echo "更新成功";
                    }
                } else {
                    echo "签名失败";
                }
            }
        }
    }

    public function lottmat()
    {

    }

    /**
     * @menu 卡管家开卡
     * @Author:男人的坏
     * @Date:2024-04-19 07:14
     */
    public function kgjcreateOrder($goods, $params, $UserInfo)
    {
        $path                  = '/api/card/open/submitOrder';
        $key                   = config('site.kgj_appkey');
        $kgj_aesSecret         = config('site.kgj_aesSecret');
        $data['goodsCode']     = $goods['packages_id'];
        $data['cardName']      = kgjAsc($params['certName'], $kgj_aesSecret);   //收货人
        $data['cardNo']        = kgjAsc($params['certNo'], $kgj_aesSecret);     //身份证号
        $data['receiverName']  = kgjAsc($params['certName'], $kgj_aesSecret);   //收货人
        $data['receiverPhone'] = kgjAsc($params['contactNum'], $kgj_aesSecret); //联系人话
        $data['province']      = $params['postProvinceName'];                   //省
        $data['city']          = $params['postCityName'];                       //市
        $data['county']        = $params['postDistrictName'];                   //区县
        $data['address']       = kgjAsc($params['postAddr'], $kgj_aesSecret);   //详细地址
        $data['outTradeNo']    = $this->auth->id.time();
        $data['prePhone']      = input('number', '');
        $checkCode             = input('checkCode', '');
        if ($checkCode) {
            $data['checkCode'] = $checkCode;
        }
        $res = kgjcurl($path, $data, $key);
        if (!empty($res['data']['orderSn'])) {
            $params['outTradeNo'] = $data['outTradeNo'];
            $this->model->orderCreateAdd($params, $UserInfo, $goods, $res['data']['orderSn']);
            $this->success('申领成功');
        } else {
            $this->error('开卡失败：'.$res['msg']);
        }
    }

    /**
     * @menu 自助开卡
     * @Author:男人的坏
     * @Date:2024-04-19 07:14
     */
    public function self_help($goods, $params, $UserInfo)
    {
        $this->model->orderCreateAdd($params, $UserInfo, $goods, '');
        $this->success('申领成功');
    }

    /**
     *信息
     */
    public function orderimage()
    {
        $card_type   = input('card_type');
        $image       = input('post.image');
        $order_id    = input('order_id');
        $pay_channel = input('pay_channel');
        $phone       = input('phone');
        if (!$order_id) {
            $this->error('缺少参数');
        }
        if ($card_type == 1 && !$image || $pay_channel == 2 && !$image) {
            $this->error('请上传图片');
        }
        if ($card_type == 2 && !Validate::regex($phone, "^1\d{10}$")) {
            $this->error(__('手机号格式不对'));
        }
        $user_id = input('user_id');
        $where   = ['id' => $order_id];
        if (!$user_id) {
//            $where['user_id'] = $this->auth->id;
        } else {
//            $where['user_id'] = $user_id;
        }
//        dump($where);exit();
        $ordreInfo = $this->model->where($where)->find();
        if (!$ordreInfo) {
            $this->error('订单不存在');
        }
        if ($ordreInfo['audit_status'] == 1) {
            $this->error('请等待审核');
        }
        if ($ordreInfo['audit_status'] == 2) {
            $this->error('已经审核通过请勿重复上传');
        }
        if ($ordreInfo['audit_status'] == 3 || $ordreInfo['error_msg']) {
            $ordreInfo->baoxiao_status = '-2';
        }
        $ordreInfo->audit_status = 1;
        if ($card_type == 1) {
            $ordreInfo->image = $image;
        }
        if ($card_type == 2) {
            if ($pay_channel == 2) {
                $ordreInfo->twoimage = $image;
            }

//            $ordreInfo->chong_phone  = $chong_phone;
        }
        if ($ordreInfo->order_status != 1) {
//            $ordreInfo->order_status = 1;
//            $ordreInfo->is_up        = 2;
        }
        if ($phone) {
            $ordreInfo->phone = $phone;
        }
        $ordreInfo->reason            = '';
        $ordreInfo->audit_upload_time = time();
        $ordreInfo->save();
        $this->success('提交成功');

    }
}
